import { project_info, project_list } from '@/api/project'

const getDefaultState = () => {
  return {
    projectTitle: '请选择项目',
    currentProjectId: 0,
    projectLogo: '',
    projectPicture: '',
    projectList: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_PROJECT_ID: (state, id) => {
    state.currentProjectId = parseInt(id)
  },
  SET_TITLE: (state, title) => {
    state.projectTitle = title
  },
  SET_LOGO: (state, logo) => {
    state.projectLogo = logo
  },
  SET_PIC: (state, pic) => {
    state.projectPicture = pic
  },
  RESET_PROJECT: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_PROJECT_LIST: (state, list) => {
    state.projectList = list
  }
}

const actions = {
  getProjectInfo({ commit }, id) {
    return new Promise((resolve, reject) => {
      project_info(id).then(response => {
        const { data } = response
        commit('SET_PROJECT_ID', data.id)
        commit('SET_TITLE', data.name)
        commit('SET_LOGO', process.env.VUE_APP_BASE_API + data.logo)
        commit('SET_PIC', process.env.VUE_APP_BASE_API + data.picture)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getProjectList({ commit }) {
    return new Promise((resolve, reject) => {
      project_list().then(response => {
        const { data } = response
        commit('SET_PROJECT_LIST', data.list)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  removeProjectInfo({ commit }) {
    commit('RESET_PROJECT')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

